package com.eqdd.yiqidian.kotlin.net

import com.lzy.okgo.callback.AbsCallback
import okhttp3.Response
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * Created by jhj on 18-6-27.
 */
abstract class HttpCallback<T> : AbsCallback<T>() {


    override fun convertResponse(response: Response?): T? {
        val str = response?.body()?.string()
        var result: HttpResult<T>? = null
        try {
            result = HttpResult<T>().parseJson(str, getClazz())
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result?.items
    }

    /**
     * 获取泛参数实际类型
     */
    fun getClazz(): Type {
        //获取当前类带有泛型的父类
        val clazz = this.javaClass.genericSuperclass
        return if (clazz is ParameterizedType) {
            //获取父类的泛型参数（参数可能有多个，获取第一个）
            clazz.actualTypeArguments[0]
        } else {
            clazz
        }
    }
}